Skip to content


tag  jupyter  tips  ai  deep learning  beginner  regression  reinforcement learning  q learning  gym  gymnasium  ardupilot  None  ros2  dds  micro ros  xrce  sitl  plugin  gazebo  garden  SITL  debug  rangefinder  pymavlink  mavros  distance sensor  system_time  timesync  cmake  gtest  ctest  101  cpp  c++  format  fmt  multithreading  spdlog  cyclonedds  eprosima  fastdds  aptly  apt  repository  repo  local  mirror  encryption  pgp  docker  arm  container  state  networking  network  nvidia  python  app  devcontainer  gui  tutorial  volume  mount  compose  multi-stage  stage  docker compose  git  bundle  submodules  github  hooks  pre-commit  lxd  lxc  x11  profile  vscode  marpit  presentation  marp  markdown  mermaid  mkdocs  video  ffmpeg  gstreamer  cheat-sheet  sdp  v4l2loopback  gi  kml  geo  gis  spatial  gdal  ogr  raster  vector  snippets  cheat Sheet  asyncio  future  click  cli  cupy  numpy  gpu  dev container  deb  debian  package  setup  stdeb  project  hydra  yaml  configuration  matplotlib  3d  subplot  open3d  point cloud  template  black  isort  templates  cookiecutter  docs  project document  docstrings  flake8  linter  git-hook  mypy  unittest  pytest  pylint  from a-z  fixture  scope  logging  pytest.ini  mock  parameterize  enum  flag  iterator  generator  yml  logging config  tuple  namedtuple  typing  annotation  generic  literal  protocol  self  typed dict  typevar  pyzmq  zmq  opencv  msgpack  slam  cartographer  action  namespace  remap  control2  demo  diff-drive  ignition  ros2_control  effort  velocity  gdb  qos  plugins  msg  node  zero-copy  shm  algorithm  calibration  diff  pid  dev  colcon  colcon_cd  settings  behavior  py_trees  bt  behavior_trees  blackboard  plot  visualization  debugging  diagnostic  DiagnosticTask  diagnostics  tutorials  gst  math  apm  rat_runtime_monitor  bag  rosbag  rosbags  tools  ros  web  rosbridge  vue  binding  discovery  gazebo-classic  launch  spawn  model  cook  camera  sensors  gps  imu  ray  gazebo_ros_ray_sensor  lidar  ultrsonic  range  ultrasonic  gazebo classic  wrench  urdf  odom  gz  sdf  world  vscode tips  gazebogz-sim-joint-position-controller-system  bridge  simulation  ros_gz_bridge  ign  xacro  diff_drive  odometry  joint_state  argument  OpaqueFunction  DeclareLaunchArgument  LaunchConfiguration  tmux  nav  test  rclpy  goal abort  cancel goal  action client  action server  custom messages  executor  MultiThreadedExecutor  SingleThreadedExecutor  param  dynamic-reconfigure  service  client  setup.py  package.xml  parameter  parameters  custom  msgs  executers  pub  sub  rqt  rviz  rviz2  pose  marker  tf2  local_setup  rosdep  package manager  project settings  vcstool  robot_state_publisher  urdf_to_graphiz  joint  link  zenoh  tags  hands on  webinar  cross-compiler  esp32  nano  jetson  arduino  i2c  sensor  mb1202  uart  serial  tfmini  rpi  teensy  microros  config  material  workshope  texture  joints  tmuxp  loop device  rootfs  embedded  zah  linux  rm  ubuntu  sudo  sudoers  nopasswd  visudo  udev  key  gpg  sign  commands  update-alternative  dpkg  ip  ss  netstat  snap  deploy  ssh  systemd  socat  udp  tc  mtu  select  robotics  path planning  trajectory  speed  pcl  kalman_filter  kalman  filter  control  code  extensions  remote  json  schema  yocto  poky  qemu  projects  courses to follow  matrix  graphics  rotation  2d  course  vision  drone  quad  uav  design  vrx  buoyancy 

Part3 - Simple python Node with parameter

Basic ROS2 node with parameter, declare, read with type, set from command line or using yaml file, get and set from command line or gui


Objective#

  • Declare parameter
  • Manage params from cli
  • Set node params with launch file

Code example#

import rclpy
from rclpy.node import Node

class TestParams(Node):

    def __init__(self):
        super().__init__('test_params_rclpy')

        self.declare_parameter('my_str')
        self.declare_parameter('my_int', value=10)
        self.declare_parameter('my_double_array')

        timer_period = 2
        self.timer = self.create_timer(timer_period, self.timer_callback)

    def timer_callback(self):
        my_param = self.get_parameter('my_str').get_parameter_value().string_value
        my_param_int = self.get_parameter("my_int").get_parameter_value().integer_value
        self.get_logger().info(f"Hello {my_param}! with int data: {my_param_int}")

def main(args=None):
    rclpy.init(args=args)
    node = TestParams()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

if __name__ == "__main__":
    main()

Manage params from cli#

Run node with param#

Note

Run node with arguments from CLI --ros-args -p <param_name>:=<param_value>

ros2 run basic simple_param --ros-args -p my_str:=world
# Result
[INFO] [1649226981.611616597] [test_params_rclpy]: Hello world! with int data: 10
[INFO] [1649226983.604038327] [test_params_rclpy]: Hello world! with int data: 10

Manage params from cli#

# list params from all running nodes
ros2 param list
# Result 
/simple_params:
  my_double_array
  my_int
  my_str
  use_sim_time

YAML file#

simple.yaml
simple_params:
  ros__parameters:
    my_str: "world from yaml"
    my_int: 100
    my_double_array: [1.0, 2.0, 3.0]

Warning

ros__parameters with double underline

Run with yaml#

terminal1
ros2 run basic simple_param --ros-args --params-file /home/user/dev_ws/src/basic/config/simple.yaml
[INFO] [1649227913.033306747] [simple_params]: Hello world from yaml! with int data: 100
[INFO] [1649227915.025466940] [simple_params]: Hello world from yaml! with int data: 100

Params yaml and launch file#

  • place yaml file in config syb folder
  • copy config folder to output folder using setup.py

yaml copy
data_files=[
        ('share/ament_index/resource_index/packages', ['resource/' + package_name]),
        ('share/' + package_name, ['package.xml']),
        (os.path.join("share", package_name), glob("launch/*.launch.py")),
        (os.path.join("share", package_name, "config"), glob("config/*")),
    ],
simple_param_yaml.launch.py
# with yaml file
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
    ld = LaunchDescription()
    config = os.path.join(
        get_package_share_directory('basic'),
        'config',
        'simple.yaml'
        )

    node=Node(
        name="simple_params",
        package = 'basic',
        executable = 'simple_param',
        parameters = [config]
    )
    ld.add_action(node)
    return ld

Warning

The name argument in the launch Node object must be the same in the param yaml file

simple_param.launch.py
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
    ld = LaunchDescription()

    node=Node(
        name="simple_params",
        package = 'basic',
        executable = 'simple_param',
        parameters = [
            {"my_str": "hello from launch"},
            {"my_int": 1000},
            {"my_double_array": [1.0, 10.0]}
        ]
    )
    ld.add_action(node)
    return ld

References#